import 'package:dio/dio.dart';
import 'package:package_model/package_model.dart';
import 'package:package_model/url_data.dart';
import 'package:regsiter_center/register_model.dart';
import 'package:user_data_model/data/token_data.dart';
import 'package:user_data_model/token_util/auth_by_form.dart';
import 'package:user_data_model/user_bloc.dart';
import 'package:fresh/fresh.dart' as fresh;
import 'package:fresh_dio/fresh_dio.dart';
/**
 *
 * @ProjectName:    user_data_model
 * @ClassName:      user_register_item
 * @Description:    dart类作用描述
 * @Author:         孙浩
 * @QQ:             243280864
 * @CreateDate:     2021/1/28 11:42 PM
 */
class UserRegister extends RegisterModel {
  Dio _baseDio;

  void initDio(Dio d) {
    _baseDio = d;
  }

  factory UserRegister() =>_getInstance();
  static UserRegister get instance => _getInstance();
  static UserRegister _instance;
  UserRegister._internal() {
    // 初始化
  }
  static UserRegister _getInstance() {
    if (_instance == null) {
      _instance = new UserRegister._internal();
    }
    return _instance;
  }

  Dio get baseDio => _baseDio;



  @override
  unbindToken() {
    UserBloc.instance.unRegisterUser();
  }

  @override
  bindToken(String token, String refreshToken) async {
    UserBloc.instance.bindToken(token);
    InMemoryTokenStorage _memoryTokenStorage = InMemoryTokenStorage();
    await _memoryTokenStorage.write(token);
    _baseDio.interceptors.add(AurhFreshByForm.oAuth2(
      tokenStorage: InMemoryTokenStorage(),
      refreshToken: (token, client) async {
        var res = await Dio().post<TokenData>(StaticUrl.BaseUrl+"appapi/account/refreshToken",data: {
          "refreshToken":token.refreshToken
        });
        TokenData _data = res.data;
        return OAuth2Token(accessToken: _data.data.accessToken,refreshToken: _data.data.refreshToken);
      },
      tokenHeader:(OAuth2Token t){
        return {"Authorization:":"${t.accessToken}"};
      }
    ),);
  }

}
